class CritiquesController < ApplicationController
  before_filter :login_required
  
  def index
  end
  
  def enter
    render(:partial=>"critiques/enter", :object=>Photo.find(params[:id]))
  end

  def save
    critique = Critique.new(params[:critique])
    critique.user_id = session[:user]
    critique.photo_id = params[:id]
    critique.save
    flash[:notice] = "Your critique was successfully saved."
    redirect_to :controller=>"gallery",:action=>"view",:id=>params[:id]
  end

  def cancel
    render(:partial=>"gallery/write_critique", :object=>Photo.find(params[:id]))
  end

  def rate
    c_r = CritiqueRating.find_by_user_id_and_critique_id(session[:user], params[:id])
    if c_r
      if params[:critique_rating][:rate] == 0
         c_r.destroy
      else
         c_r.update_attribute(:rate, params[:critique_rating][:rate])
      end
    else
      c_r = CritiqueRating.new(params[:critique_rating])
      c_r.user_id = session[:user]
      c_r.critique = Critique.find(params[:id])
      c_r.save
    end
    render(:partial=>"critiques/critique_profile", :object=>c_r.critique)
  end

  def enter_reply
    render(:partial=>"critiques/enter_reply", :object=>Critique.find(params[:id]))
  end

  def save_reply
    reply = Reply.new(params[:reply])
    reply.user_id = session[:user]
    reply.critique_id = params[:id]
    reply.save
    flash[:notice] = "Your reply was successfully saved."
    redirect_to :controller=>"gallery",:action=>"view",:id=>reply.critique.photo
  end

  def cancel_reply
    render(:partial=>"critiques/reply_link", :object=>Critique.find(params[:id]))
  end

  def delete_reply
    to_be_del = Reply.find(params[:id])
    photo = to_be_del.critique.photo
    to_be_del.destroy
    flash[:notice] = "Your reply was deleted."
    redirect_to :controller=>"gallery",:action=>"view",:id=>photo
  end

  def enter_reply_reply
    render(:partial=>"critiques/enter_reply_reply", :object=>Reply.find(params[:id]))
  end

  def save_reply_reply
    parent = Reply.find(params[:id])
    child = parent.children.create(params[:reply])
    child.user_id = session[:user]
    child.critique_id = parent.critique_id
    child.save
    flash[:notice] = "Your reply was successfully saved."
    redirect_to :controller=>"gallery",:action=>"view",:id=>child.critique.photo
  end

  def cancel_reply_reply
    render(:partial=>"critiques/reply_reply_link", :object=>Reply.find(params[:id]))
  end
  
  def ratings
    @crit = Critique.find(params[:id])
  end
end
